// src/composables/useExport.js
import { ref } from 'vue';
import { useDateFormat, useNow } from '@vueuse/core';

export const useExport = (options = {}) => {
  const {
    exportApi, // 导出API函数
    filenameBase = 'export_excel_', // 文件名基础
    excludeFields = ['selection', 'operation'], // 默认排除的字段
    sheetName = 'Sheet1', // 默认sheet名称
    types = ['xlsx'], // 允许导出的文件类型
  } = options;

  // 生成带时间戳的文件名
  const generateFilename = () => {
    const timestamp = useDateFormat(useNow(), 'YYYYMMDDHHmmss').value;
    return `${filenameBase}${timestamp}.xlsx`;
  };

  // 导出配置对象
  const exportConfig = ref({
    remote: true,
    filename: generateFilename(),
    sheetName,
    mode: 'current',
    modes: ['current', 'selected', 'all', 'empty'],
    type: 'xlsx',
    types,
    excludeFields,
    original: false,
    useStyle: false,
    async exportMethod({ options: exportOptions }) {
      try {
        const params = {
          ids: exportOptions.data.map((item) => item.id),
          fields: exportOptions.columns
            .filter((col) => !excludeFields.includes(col.field))
            .map((column) => ({
              field: column.field,
              title: column.title,
            })),
          sheetName: exportOptions.sheetName,
          type: exportOptions.type,
          mode: exportOptions.mode,
          isHeader: exportOptions.isHeader,
          original: exportOptions.original,
          fileName: generateFilename(),
        };

        const response = await exportApi(params, { responseType: 'blob' });

        // 处理文件名
        let downloadFileName = generateFilename();
        const contentDisposition = response.headers['content-disposition'];
        if (contentDisposition) {
          const match = contentDisposition.match(
            /filename\*?=["']?(?:UTF-8'')?([^;"']+)["']?/i,
          );
          if (match && match[1]) {
            try {
              downloadFileName = decodeURIComponent(match[1]);
            } catch (e) {
              downloadFileName = match[1];
            }
          }
        }

        // 创建并下载文件
        const blob = new Blob([response.data], {
          type: response.headers['content-type'],
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = downloadFileName;
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      } catch (error) {
        console.error('Export failed:', error);
        throw error;
      }
    },
  });

  return { exportConfig };
};
